/**
 * Created by jiachneyu on 2018/3/22.
 */
const db = require('../db');

const msgHandle =  async (method,body)=>{
    if(method === 'get'){
        return await getMsg();
    }
    else {
        return await sendMsg(body);
    }
}

const getMsg = async ()=>{
    let returnJson = {};
    const collection = db.get('message');
    await collection.find({}).then((res)=>{
        res = res.reverse();
        if(res.length > 10){
            res = res.filter((val,index)=>{
                return index < 10
            })
        }
        returnJson = {
            code: 1,
            msg: '查询成功',
            data: res
        }
        db.close();
    }).catch(err=>{
        console.log(err);
        returnJson = {
            code: -1,
            msg: '查询失败'
        };
        db.close();
    })
    return returnJson
}

const sendMsg = async (body,ctx)=>{
    let returnJson = {};
    const collection = db.get('message');
    await collection.insert(body).then((res)=>{
        console.log(res);
        returnJson = {
            code: 1,
            msg: '插入成功'
        }
        db.close();
    }).catch(err=>{
        console.log(err);
        returnJson = {
            code: -1,
            msg: '插入失败'
        };
        ctx.response.body = returnJson;
        db.close();
    })
    return returnJson;
}

module.exports = msgHandle;